﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControl_ControlDoiGiaHangBan : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridSearch(Session["sitecode"].ToString());
        }
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        txtSoNV.Text = "New";
        txtMaHang.Text = "";
        txtTenHang.Text = "";
        txtOldPrice.Text = "";
        txtNewPrice.Text = "";
        if (ViewState["KhoHangTemp"] != null)
        {
            ViewState["KhoHangTemp"] = null;

        }
        grvProduct.DataSource = null;
        grvProduct.DataBind();
        ViewState["flag"] = true;
    }
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string docno = "";
            if ((bool)ViewState["flag"])
            {
                docno = dt.GetDataDepend(str, "k_getDocNoDynamic", CommandType.StoredProcedure, ref error,
                    new SqlParameter("@Type", "F"));
                ViewState["flag"] = true;
            }
            else
            {
                docno = txtSoNV.Text;
            }
            int i = 1;
            foreach (GridViewRow grv in grvProduct.Rows)
            {
                Label lblMaHang = (Label)grv.FindControl("lblMaHang");
               
                Label lblGiaCu = (Label)grv.FindControl("lblGiaCu");
                Label lblGiaMoi = (Label)grv.FindControl("lblGiaMoi");
                
                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_inssertNVChangePrice", ref error,
                    new SqlParameter("@itemkey", lblMaHang.Text),
                    new SqlParameter("@docno", docno),
                    new SqlParameter("@Type", "F"),
                    new SqlParameter("@docdate", txtDate.Text),
                    new SqlParameter("@stocprice", float.Parse(lblGiaMoi.Text)),
                    new SqlParameter("@stockcost", float.Parse(lblGiaCu.Text)),
                    new SqlParameter("@sitecode",Session["sitecode"].ToString()),
                    new SqlParameter("@i",i));
                i++;
            }
           
            if (ViewState["KhoHangTemp"] != null)
            {
                ViewState["KhoHangTemp"] = null;

            }

            grvProduct.DataSource = null;
            grvProduct.DataBind();

            txtSoNV.Text = "";
            txtDate.Text = "";
            txtMaHang.Text = "";
            txtTenHang.Text = "";
            txtOldPrice.Text = "";
            txtNewPrice.Text = "";

            uscMsgBox1.AddMessage("Lưu thông tin thành công", uscMsgBox.enmMessageType.Success);


        }
        catch (Exception ex)
        {
            uscMsgBox1.AddMessage("Hệ thống đang bảo trì", uscMsgBox.enmMessageType.Success);
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    protected void imgBtnDelete_Click(object sender, ImageClickEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_deleteChangeprice", ref error,
                 new SqlParameter("@DocNo", txtSoNV.Text));
            if (kq)
            {
               
                grvProduct.DataSource = null;
                grvProduct.DataBind();
                if (ViewState["KhoHangTemp"] != null)
                {
                    ViewState["KhoHangTemp"] = null;

                }
                txtSoNV.Text = "";
                txtMaHang.Text = "";
                txtTenHang.Text = "";
                txtOldPrice.Text = "";
                txtNewPrice.Text = "";
                uscMsgBox1.AddMessage("Nghiệp vụ xóa thành công", uscMsgBox.enmMessageType.Success);

            }
            else
            {
                uscMsgBox1.AddMessage("Hệ thống đang bảo trì", uscMsgBox.enmMessageType.Success);
            }
        }
        catch (Exception ex)
        {
            uscMsgBox1.AddMessage("Hệ thống đang bảo trì", uscMsgBox.enmMessageType.Error);
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   

    }
    protected void imgBtnFind_Click(object sender, ImageClickEventArgs e)
    {
        TabContainer1.ActiveTabIndex = 1;
    }
    protected void grvSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblSoNV = (Label)grv.FindControl("lblSoNV");

                DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getDetailChangePrice", CommandType.StoredProcedure,
                   new SqlParameter("@DocNo", lblSoNV.Text));
                txtSoNV.Text = db.Rows[0]["docno"].ToString();
                txtDate.Text = db.Rows[0]["DocDate"].ToString();

                ViewState["KhoHangTemp"] = db;

                grvProduct.DataSource = db;
                grvProduct.DataBind();

                ViewState["flag"] = false;
                TabContainer1.ActiveTabIndex = 0;

            }
        }
        catch (Exception ex)
        {
          
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    protected void btSearch_Click(object sender, EventArgs e)
    {

    }
    protected void txtMaHang_TextChanged(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string Chuoi = txtMaHang.Text;
            int index = Chuoi.IndexOf("|");
            txtMaHang.Text = Chuoi.Substring(0, index - 1);
            txtTenHang.Text = Chuoi.Substring(index + 2, Chuoi.Length - index - 2);
            txtOldPrice.Text = dt.GetDataDepend(str, "k_getPice", CommandType.StoredProcedure, ref error,
                new SqlParameter("@itemkey", txtMaHang.Text));
            txtNewPrice.Focus();

        }
        catch
        {
            return;
        }
    }
    protected void btAdd_Click(object sender, EventArgs e)
    {
        UpdateGridProduct();
    }
    void UpdateGridProduct()
    {
        DataTable table = new DataTable();
        if (ViewState["KhoHangTemp"] != null)
        {
            table = (DataTable)ViewState["KhoHangTemp"];
            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == txtMaHang.Text)
                {
                    dr[3] = Double.Parse(txtNewPrice.Text);
                    ViewState["KhoHangTemp"] = table;
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                    return;
                }
            }

            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[0] = txtMaHang.Text;
            row[1] = txtTenHang.Text;
            row[2] = Double.Parse(txtOldPrice.Text);
            row[3] = Double.Parse(txtNewPrice.Text);

            table.Rows.Add(row);
        }
        else
        {


            DataColumn col1 = new DataColumn("Mã hàng");
            DataColumn col2 = new DataColumn("Tên hàng");
            DataColumn col3 = new DataColumn("Giá cũ");
            DataColumn col4 = new DataColumn("Giá mới");

            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.Double");
            col4.DataType = System.Type.GetType("System.Double");

            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);
            table.Columns.Add(col4);

            //Create a Row in the DataTable table
            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[col1] = txtMaHang.Text;
            row[col2] = txtTenHang.Text;
            row[col3] = Double.Parse(txtOldPrice.Text);
            row[col4] = Double.Parse(txtNewPrice.Text);

            table.Rows.Add(row);

            ViewState["KhoHangTemp"] = table;
        }
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void grvProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();
            TextBox txtGM = (TextBox)grvProduct.Rows[e.RowIndex].FindControl("txtGM");
            if ((txtGM.Text == "") || (txtGM.Text == "0"))
            {
                txtGM.Text = "1";
            }
            Double NewPrice = Double.Parse(txtGM.Text);
            DataTable table = new DataTable();
            table = (DataTable)ViewState["KhoHangTemp"];

            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == keys)
                {
                    dr[3] = NewPrice;
                    table.AcceptChanges();
                    ViewState["KhoHangTemp"] = table;

                    grvProduct.EditIndex = -1;
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                }
            }

        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTemp"] = table;
                grvProduct.EditIndex = -1;
                grvProduct.DataSource = ViewState["KhoHangTemp"];
                grvProduct.DataBind();
                return;
            }
            i++;
        }
    }
    protected void grvProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvProduct.EditIndex = -1;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void grvProduct_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvProduct.EditIndex = e.NewEditIndex;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    void BindGridSearch(string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getMasterChangePrice", CommandType.StoredProcedure,
                 new SqlParameter("@type", "F"),
                new SqlParameter("@siteCode", sitecode));
            grvSearch.DataSource = db;
            grvSearch.DataBind();
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvSearch.PageIndex = e.NewPageIndex;
        BindGridSearch(Session["sitecode"].ToString());
    }
}